package com.lst.api.controller;

import com.lst.api.constant.RedisKeysConstant;
import com.lst.api.entity.SysUser;
import com.lst.api.exception.UserInvalidException;
import com.lst.api.service.ISysUserService;
import com.lst.api.vo.request.LoginByPwdRequest;
import com.lst.api.vo.response.UserLoginResponse;
import com.lst.tools.basics.exception.BaseException;
import com.lst.tools.basics.utils.IpUtils;
import com.lst.tools.basics.utils.ValidatorUtils;
import com.lst.tools.custom.vo.JsonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 推销员相关接口
 *
 * @author Frank
 * @date 2019-12-30 10:31:37
 * @version: V1.0
 */
@Api(tags = "推销员相关接口")
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation(value = "通过用户名与密码获取token", notes = "根据用户手机名和密码获取对应的token")
    @ApiImplicitParam(paramType = "body", name = "LoginByPwdRequest", value = "请求实体", required = true, dataType = "LoginByPwdRequest")
    @PostMapping(value = "/loginByPwd")
    public JsonResponse<UserLoginResponse> getByMobileAndPwd(@RequestBody LoginByPwdRequest loginByPwdRequest,
                                                             HttpServletRequest request) {
        try {
            ValidatorUtils.validate(loginByPwdRequest);
            String userName = loginByPwdRequest.getUsername();
            String password = loginByPwdRequest.getPassword();
            SysUser sysUser = sysUserService.getValidByUserNameAndPwd(userName, password);
            if (sysUser == null) {
                throw new UserInvalidException("用户不存在或者被禁用！");
            }
            Long userId = sysUser.getUserId();
            String ip = IpUtils.getIpAddress(request);
            String tokenRedisKey = RedisKeysConstant.USER_SMALL_ROUTINE_TOKEN_PREFIX_ + userId;
            UserLoginResponse userLoginResponse = sysUserService.login(sysUser, ip, tokenRedisKey);
            LOGGER.info("Function[getByMobileAndPwd] login success. userId:{}, ip:{}, ", userId, ip);
            return JsonResponse.success(userLoginResponse);
        } catch (BaseException e) {
            LOGGER.error("Function[getByMobileAndPwd] error. errorCode:{}, errorMessage:{}, ", e.getErrorCode(), e.getMessage(), e);
            return JsonResponse.fail(e.getErrorCode(), e.getMessage());
        }
    }
}
